<?php
namespace app\home\logic;

use app\common\logic\Base;
use think\facade\App;
use think\facade\Request;

class UrlChannelRelation extends  Base {
    
    /**
     * @desc 我的渠道
     * @param array $params
     * @param int $userId
     * @return array
     * @throws \Exception
     */
    public function index($params, $userId) {
        $where[] = ['ucr_user_id', '=', $userId];
        if($params['channelName']) {
            $channelId = model('UrlChannel')
                ->where('uc_channel_name', 'like', $params['channelName'].'%')
                ->column('uc_channel_id');
            $where[] = ['ucr_channel_id', 'in', $channelId];
        }

        if($params['keyword']) {
            $urlIds = model('Url')
                ->where('keyword', 'like', '%'.$params['keyword'].'%')
                ->column('url_id');
            $where[] = ['ucr_url_id', 'in', $urlIds];
        }

        if($params['startDate'] && $params['endDate']) {
            $startTime = date('Y-m-d 00:00:00', strtotime($params['startDate']));
            $endTime = date('Y-m-d 23:59:59', strtotime($params['endDate']));
            $where[] = ['ucr_create_time', 'between', [$startTime, $endTime]];
        }else{
            if($params['startDate']) {
                $where[] = ['ucr_create_time', 'gt', date('Y-m-d 00:00:00', strtotime($params['startDate']))];
            }
            if($params['endDate']) {
                $where[] = ['ucr_create_time', 'lt', date('Y-m-d 23:59:59', strtotime($params['endDate']))];
            }
        }

        $list = App::model('UrlChannelRelation')
            ->where($where)
            ->leftJoin('Url', 'url_id = ucr_url_id')
            ->leftJoin('UrlChannel', 'uc_channel_id = ucr_channel_id')
            ->order('ucr_id', 'desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);

        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = $list['data'];
        }

        //短链接地址
        $shortUrl = model('Domain')->getDomain($userId);

        return [
            'list'       => $list,
            'params'     => $params,
            'pagination' => $pagination,
            'shortUrl'   => $shortUrl
        ];
    }


    /**
     * @desc 我的渠道
     * @param array $params
     * @param int $userId
     * @return array
     * @throws \Exception
     */
    public function detail($params, $userId) {
        $urlGroupRelationWhere = [
            ['ucr_user_id', '=', $userId],
            ['ucr_channel_id', '=', $params['id']]
        ];
        $list = model('UrlChannelRelation')
            ->where($urlGroupRelationWhere)
            ->leftJoin('Url', 'url_id = ucr_url_id')
            ->leftJoin('UrlChannel', 'uc_channel_id = ucr_channel_id')
            ->limit(100)
            ->select();

        //渠道列表
        $field = [
            'uc_channel_id AS channelId',
            'uc_channel_name AS channelName',
            'uc_channel_key AS channelKey',
            'uc_channel_code AS channelCode'
        ];
        $groupWhere = [
            ['uc_user_id', '=', $userId],
            ['uc_channel_id', '=', $params['id']]
        ];
        $channelInfo = model('UrlChannel')
            ->field($field)
            ->where($groupWhere)
            ->find();

        //查询短链接信息,筛选已添加到分组里面的
        $urlWhere[] = ['user_id', '=', $userId];
        $urlIds = model('UrlChannelRelation')
            ->where($urlGroupRelationWhere)
            ->select()
            ->column('ucr_url_id');
        if($urlIds) {
            $urlWhere[] = ['url_id', 'not in', $urlIds];
        }
        $urlList = model('Url')
            ->field('url_id,keyword,link')
            ->where($urlWhere)
            ->limit(100)
            ->order('url_id', 'desc')
            ->select();

        //短链接地址
        $shortUrl = model('Domain')->getDomain($userId);

        return [
            'list'        => $list,
            'urlList'     => $urlList ? output_format($urlList) : [],
            'params'      => $params,
            'shortUrl'    => $shortUrl,
            'channelInfo' => $channelInfo
        ];
    }

    /**
     * @desc 添加分组关联
     * @param array $params
     * @param int $userId
     * @return bool
     * @throws \Exception
     */
    public function add($params, $userId) {
        $where = [
            ['ucr_user_id', '=', $userId],
            ['ucr_url_id', 'in', $params['urlId']],
            ['ucr_channel_id', '=', $params['channelId']]
        ];
        $urlGroupRelation = model('UrlChannelRelation')
            ->where($where)
            ->find();


        if($urlGroupRelation) {
            $this->errorCode = EC_HOME_URL_CHANNEL_RELATION_ALREADY_EXIST;
            return  false;
        }
        $insertData = [];
        foreach ($params['urlId'] as $v) {
            $insertData[] = [
                'ucr_url_id'      => $v,
                'ucr_user_id'     => $userId,
                'ucr_channel_id'  => $params['channelId'],
                'ucr_create_time' => date('Y-m-d H:i:s')
            ];
        }
        $result = model('UrlChannelRelation')->insertAll($insertData);
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }

    /**
     * @desc 删除分组关联
     * @param int $id
     * @param int $userId
     * @return bool
     * @throws \Exception
     */
    public function del($id, $userId) {
        $where = [
            ['ucr_id', '=', $id],
            ['ucr_user_id', '=', $userId]
        ];
        $urlGroupRelation = model('UrlChannelRelation')
            ->where($where)
            ->find();
        if(!$urlGroupRelation) {
            $this->errorCode = EC_HOME_URL_CHANNEL_RELATION_NOT_EXIST;
            return  false;
        }
        $result = model('UrlChannelRelation')
            ->where($where)
            ->delete();

        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }
}
